<template>
	<div class="sys-user-edit-container">
		<el-card class="breadcrumb-card card-form" :style="{height:formHeight+'px'}">
			<!-- 路径导航 -->
			<div slot="header" class="breadcrumb-header">
				<el-page-header @back="$router.back()" title="用户管理" content="编辑"/>
				<div class="btn-list">
					<el-button size="small" type="primary" @click="submit">保存<i class="el-icon-check el-icon--right"/></el-button>
					<el-button size="small" @click="$router.back()">取消<i class="el-icon-close el-icon--right"/></el-button>
				</div>
			</div>
			<!-- form表单 -->
			<el-scrollbar class="form edit-form">
				<el-form ref="form" :model="form" label-width="90px" :show-message="false" :rules="rules">
					<el-row :gutter="100">
						<el-col :span="12">
							<el-form-item label="用户姓名:" prop="name">
								<el-input size="medium" v-model="form.name" placeholder="请输入姓名" maxlength="10"></el-input>
							</el-form-item>
						</el-col>		
						<el-col :span="12" v-if="!form.id">
							<el-form-item label="登录账号:" prop="loginAccount">
								<el-input size="medium" v-model="form.loginAccount" placeholder="请输入手机号码"></el-input>
							</el-form-item>
						</el-col>	
						<el-col :span="12" v-if="form.id">	
							<el-form-item label="手机号码:" prop="phone">
								<el-input size="medium" v-model="form.phone" placeholder="请输入手机号码"></el-input>
							</el-form-item>
						</el-col>		
					</el-row>
					<el-row :gutter="100" v-if="!form.id">
						<el-col :span="12">
							<el-form-item label="登录密码:" prop="loginPassword">
								<el-input size="medium" show-password v-model="form.loginPassword" placeholder="请输入密码"></el-input>
							</el-form-item>
						</el-col>		
						<el-col :span="12">	
							<el-form-item label="确认密码:" prop="confirmLoginPassword">
								<el-input size="medium" show-password v-model="form.confirmLoginPassword" placeholder="请输入确认密码"></el-input>
							</el-form-item>
						</el-col>		
					</el-row>
					<el-row :gutter="100">
						<el-col :span="12">
							<el-form-item label="用户类型:" prop="type">
								<el-select size="medium" v-model="form.type" placeholder="请选择">
									<el-option
										v-for="item in typeOptions"
										:key="item.value"
										:label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>	
						<el-col :span="12">
							<el-form-item label="允许登录:" prop="status">
								<el-switch size="medium" v-model="form.status" active-value="0" inactive-value="1" active-color="#3c8dbc" inactive-color="#eee">
								</el-switch>
							</el-form-item>
						</el-col>		
					</el-row>	
					<el-row :gutter="100">
						<el-col :span="12">
							<el-form-item label="头像:" prop="avatar">
								<el-upload
								ref="upload"
								class="avatar-uploader"
								action="http://api.mvvm.site/adminApi/sys/upload"
								:show-file-list="false"
								:on-success="uploadSuccess"
								:before-upload="beforeUpload">
								<img v-if="form.avatar" :src="form.avatar" class="avatar">
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
							</el-form-item>
						</el-col>		
						<el-col :span="12">	
							<!-- 角色列表 -->
							<el-form-item label="分配角色:" prop="roleId">
								<el-table :height="200" :show-header="false" ref="roleTable" size="medium" style="width: 100%" :data="roleList" @current-change="roleChange">
									<el-table-column type="selection" width="55"/>
									<el-table-column prop="name" label="角色名称"/>
								</el-table>
							</el-form-item>	
						</el-col>		
					</el-row>			
				</el-form>
			</el-scrollbar>
		</el-card>		
	</div>
</template>

<script>
import sysApi from '@/api/sysApi'	
import sysUserApi from '@/api/sysUserApi'		
import sysRoleApi from '@/api/sysRoleApi'	
	
export default {
	name: 'sysUserEdit',
	data () {
		/* 校验密码一致性 */
		var validatePassword = (rule, value, callback) => {
			if (value !== this.form.loginPassword) {
				callback(new Error('两次输入密码不一致!'));
			} else {
				callback();
			}
		};
		return {
			formHeight: 0,
			/* 表单数据 */
			form: {},
			/* 用户类型 */
			typeOptions: [{value: '0',label: '管理员'},{value: '1',label: '普通用户'}],
			/* 角色列表 */
			roleList: [],
			/* 校验规则 */
			rules: {
				name: [{required: true, message: '请输入用户姓名'}],
				loginAccount: [
					{required: true, message: '请输入登录账号'},
					{pattern: /^1[34578]\d{9}$/, message: '手机号码格式错误'}
				],
				phone: [
					{required: true, message: '请输入手机号码'},
					{pattern: /^1[34578]\d{9}$/, message: '手机号码格式错误'}
				],
				loginPassword: [{required: true, message: '请输入密码'}],
				confirmLoginPassword: [
					{required: true, message: '请输入确认密码'},
					{validator: validatePassword}
				],
				type: [{required: true, message: '请选择用户类型'}]
			}
		}
	},
	mounted () {
		this.$nextTick(() => { 
			let h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			this.formHeight = h -80;
		});
	},
	created () {
		//获取详情
		if(this.$route.query.id){
			this.getDetail();
		}
		//获取角色列表
		this.getSysRoleList();
	},
	methods: {
		/* 获取详情 */
		async getDetail () {
			const result = await sysUserApi.sysUserDetail(this.$route.query.id);
			this.form = result.data;
		},
		/* 获取角色列表 */
		async getSysRoleList () {
			const result = await sysRoleApi.sysRoleList({pageNo: 1, pageSize: 100});
			this.roleList = result.data.list;
		},
		/* 头像上传 */
		uploadSuccess(res, file) {
			if(res.code == 200){
				this.form.avatar = res.data.url
			}else{
				this.$message.error('上传图片失败!');
			}
		},
		/* 头像上传 */
		beforeUpload(file) {
			const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
			const isLt2M = file.size / 1024 / 1024 < 2;
			if (!isImg) {
				this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!');
			}
			return isImg && isLt2M;
		},
		/* 选择角色 */
		roleChange (row) {
			this.$refs.roleTable.clearSelection();
			this.$refs.roleTable.toggleRowSelection(row);
			this.form.roleId = row.id;
		},
		/* 提交表单 */
		async submit () {
			this.$refs.form.validate(async (valid, error) => {
				/* 校验数据 */
				if(valid){
					let result;
					if(this.form.id){
						//编辑
						result = await sysUserApi.updateUser(this.form);
					}else{
						//新增
						result = await sysUserApi.addUser(this.form);
					}
					if(result.code == 200){
						this.$message.success('操作成功!');
						this.$router.back();
					}else{
						this.$message.error(result.msg);
					}
				}else{
					this.$message.error({message: error[Object.keys(error)[0]][0].message, duration: 1000})
				}
			})
		}
	}
}	
</script>

<style lang="scss">
.sys-user-edit-container{
	.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
}	
</style>
